﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Avalonia;
using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using FluentAvalonia.UI.Controls;
using iOSClub.App.Desktop.Views;
using iOSClub.App.Share;
using iOSClub.App.Share.Serves;
using Newtonsoft.Json;
using NPOI.XSSF.UserModel;

namespace iOSClub.App.Desktop.Pages;

public partial class ManagePage : UserControl
{
    private List<MemberModel> List { get; set; } = [];

    private static readonly string[] ChooseType =
    [
        "姓名",
        "学号",
        "学院",
        "政治面貌",
        "性别",
        "班级",
        "手机号码"
    ];

    public ManagePage()
    {
        InitializeComponent();
    }

    protected override async void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        var view = ViewOpera.GetView<MainView>(this);
        if (view == null) return;
        using var ios = new iOSServer(view.Jwt);
        List = await ios.GetStudents();
        DataGrid.ItemsSource = new DataGridCollectionView(List);
        Ring.IsVisible = false;
        DataGrid.IsVisible = true;
        ChooseBox.ItemsSource = ChooseType;
        ChooseBox.SelectedItem = ChooseType[0];
    }

    private async void DownloadClick(object? sender, RoutedEventArgs e)
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;

        var result = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions()
        {
            DefaultExtension = ".xlsx",
            Title = "将数据保存到"
        });

        if (result == null) return;

        var table =
            (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(DataGrid.ItemsSource),
                typeof(DataTable))!;

        await using var fs = await result.OpenWriteAsync();
        using var workbook = new XSSFWorkbook();
        var excelSheet = workbook.CreateSheet("Sheet1");

        var columns = new List<string>();
        var row = excelSheet.CreateRow(0);
        var columnIndex = 0;

        foreach (DataColumn column in table.Columns)
        {
            columns.Add(column.ColumnName);
            row.CreateCell(columnIndex).SetCellValue(column.ColumnName);
            columnIndex++;
        }

        var rowIndex = 1;
        foreach (DataRow destroy in table.Rows)
        {
            row = excelSheet.CreateRow(rowIndex);
            var cellIndex = 0;
            foreach (var col in columns)
            {
                row.CreateCell(cellIndex).SetCellValue(destroy[col].ToString());
                cellIndex++;
            }

            rowIndex++;
        }

        workbook.Write(fs);
    }

    private void SearchSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (sender is not FAComboBox comboBox) return;
        var s = comboBox.SelectedItem as string;
        if (string.IsNullOrEmpty(s)) return;
        switch (s)
        {
            case "学院":
                SearchComboBox.IsVisible = true;
                SearchComboBox.ItemsSource = SignRecord.Academies;
                SearchBox.IsVisible = false;
                break;
            case "政治面貌":
                SearchComboBox.IsVisible = true;
                SearchComboBox.ItemsSource = SignRecord.PoliticalLandscapes;
                SearchBox.IsVisible = false;
                break;
            case "性别":
                SearchComboBox.IsVisible = true;
                SearchComboBox.ItemsSource = SignRecord.Genders;
                SearchBox.IsVisible = false;
                break;
            default:
                SearchBox.IsVisible = true;
                SearchComboBox.IsVisible = false;
                break;
        }
    }

    private void SearchBoxKeyDown(object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;
        if (string.IsNullOrEmpty(SearchBox.Text)) return;
        var c = ChooseBox.SelectedItem as string;
        if (string.IsNullOrEmpty(c)) return;
        DataGrid.ItemsSource = c switch
        {
            "姓名" => List.Where(x => x.UserName.StartsWith(SearchBox.Text)),
            "学号" => List.Where(x => x.UserId.StartsWith(SearchBox.Text)),
            "班级" => List.Where(x => x.ClassName.StartsWith(SearchBox.Text)),
            "手机号码" => List.Where(x => x.PhoneNum.StartsWith(SearchBox.Text)),
            _ => DataGrid.ItemsSource
        };
    }

    private void SearchComboBoxChanged(object? sender, SelectionChangedEventArgs e)
    {
        var s = SearchComboBox.SelectedItem as string;
        if (string.IsNullOrEmpty(s)) return;
        var c = ChooseBox.SelectedItem as string;
        if (string.IsNullOrEmpty(c)) return;
        DataGrid.ItemsSource = c switch
        {
            "学院" => List.Where(x => x.Academy == s),
            "政治面貌" => List.Where(x => x.PoliticalLandscape == s),
            "性别" => List.Where(x => x.Gender == s),
            _ => DataGrid.ItemsSource
        };
    }
}